package com.yao.controller;

import com.yao.context.BaseContext;
import com.yao.pojo.Category;
import com.yao.pojo.Result;
import com.yao.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
@Api(tags = "文章分类相关接口")
public class CategoryController {

    private CategoryService categoryService;

    @Autowired
    public void CategoryController(CategoryService categoryService){
        this.categoryService = categoryService;
    }

    /**
     * 获取所有文章分类
     * @return
     */
    @GetMapping
    @ApiOperation("获取所有文章分类")
    public Result<List<Category>> categoryList(){
        log.info("用户ID...{}获取文章所有分类", BaseContext.getCurrentId());

        List<Category> categoryList = categoryService.getCategoryList();
        return Result.success(categoryList);
    }

    /**
     * 新增文章分类
     * @param category
     * @return
     */
    @PostMapping
    @ApiOperation("新增文章分类")
    public Result addCategory(@RequestBody Category category){
        log.info("新增文章分类信息...{}",category);

        categoryService.addCategory(category);
        return Result.success("添加成功");
    }

    /**
     * 修改文章分类
     * @param category
     * @return
     */
    @PutMapping
    @ApiOperation("修改文章分类")
    public Result changeCategory(@RequestBody Category category){
        log.info("修改文章分类信息...{}",category);

        boolean flag = categoryService.changeCategory(category);
        if (!flag) return Result.error("无权限...");
        return Result.success("修改成功");
    }

    /**
     * 获取分类信息
     * @return
     */
    @GetMapping("/detail")
    @ApiOperation("获取分类信息")
    public Result categoryInfo(Integer id){
        log.info("根据ID获取文章分类信息...{}",id);

        Category category = categoryService.getCategory(id);
        return Result.success(category);
    }

    /**
     * 删除文章分类
     * @param id
     * @return
     */
    @DeleteMapping()
    @ApiOperation("删除文章分类")
    public Result deleteCategory(Integer id){
        log.info("根据ID删除文章分类...{}",id);

        int flag = categoryService.deleteCategory(id);

        if (flag == 1) return Result.error("该分类还存有文章");
        if (flag == 2) return Result.error("没有权限");
        return Result.success("删除成功");
    }
}
